package edu.unipd.p2t.db;

import java.io.Serializable;
import java.security.MessageDigest;
import java.util.Date;

//import android.util.Log;

/**
 * @author Tommaso Dal Sasso
 *
 */
public class Message implements Serializable {

	/**
	 * Serial version UID for objects serialization
	 */
	private static final long serialVersionUID = 1L;

	public final int MESSAGE_MAX_LENGTH = 140;

	private String author, text, hash;

	private Date date;

	private int hops_to_live;


	public Message( String author, String message, Date date, int hop ) {
		this.author = author;
		this.text = message;
		this.date = date;
		this.hops_to_live = hop;
		this.hash = generateHash();
	}


	public String generateHash() {
		return MD5( author + text );
	}


	public int getHops_to_live() {
		return hops_to_live;
	}


	public void setHops_to_live(int hopsToLive) {
		hops_to_live = hopsToLive;
	}


	public String getAuthor() {
		return author;
	}


	public String getText() {
		return text;
	}


	public String getHash() {
		return hash;
	}


	public Date getDate() {
		return date;
	}

	/**
	 * Funzione di utilità che genera il message digest del testo in input utilizzando l'algoritmo MD5
	 * @param msg testo in input
	 * @return messagge digest dell'input
	 */
	public static String MD5(String msg) {
		StringBuffer hexString=new StringBuffer();
		try{ 
			MessageDigest algorithm = MessageDigest.getInstance( "MD5" );
			algorithm.reset();
			algorithm.update(msg.getBytes());
			byte messageDigest[] = algorithm.digest();

			// Log.i(TAG,"lenght: "+Integer.toString(messageDigest.length));
			for ( int i=0; i<messageDigest.length; i++ ) {
				hexString.append( Integer.toHexString(0xFF & messageDigest[i]) );
			}
			// Log.i(TAG,"MD5: "+hexString.toString());

		}catch( Exception e ){
			// Log.e(TAG,"Eccezione MD5: ",e);
		}

		return hexString.toString();
	}
	
	@Override
	public String toString() {		
		return author + ";" + text + ";" + date + ";" + hops_to_live + ";" + hash;
	}

}
